package my.state.headfirst.good;

import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

//已投硬币状态
public class HasQuarterState implements State {


    //transient 修饰是 proxy 模式中加入的改进
    transient private Random randomWinner = ThreadLocalRandom.current();

    //transient 修饰是 proxy 模式中加入的改进
    transient private GunballMachine gunballMachine;

    public HasQuarterState(GunballMachine gunballMachine) {
        this.gunballMachine = gunballMachine;
    }

    @Override
    public void insertQuarter() {
        System.out.println("亲，已经投过了硬币,准备出出糖果吧！");
    }

    @Override
    public void ejectQuarter() {
        System.out.println("亲，退币成功！");
        gunballMachine.setState(gunballMachine.getNoQuarterState());
    }

    @Override
    public void turnCrank() {
        System.out.println("亲，稍定马上了出糖果请稍后");
        int winner = randomWinner.nextInt(10);
        //10 分之一的概率是幸运者，幸运者出两颗糖果，所以糖果数量要大于一颗
        if (winner == 0 && (gunballMachine.getCount() > 1)) {
            gunballMachine.setState(gunballMachine.getWinnerState());
        } else {
            gunballMachine.setState(gunballMachine.getSoldState());
        }

    }

    @Override
    public void dispense() {
        System.out.println("亲，请先转动摇杆");
    }
}
